<template>
	<view class="partner-profile">
		<!-- 顶部绿色背景和头像 -->

		<view class="profile-header" 	@tap="navTo(userInfo ? '/pages/user/userinfo/userinfo' : 'login')">
			<view class="header-bg"></view>
			<view class="avatar-box">
				<image class="avatar" :src="userInfo.head_portrait || headImg" />
			</view>
			<view class="name">{{
						userInfo.nickname ||
						userInfo.realname ||
							'登录/注册'
					}}</view>
		</view>
		<!-- 橙色销售数据卡片 -->
		<view class="sales-summary">
			<view class="summary-main">
				<view class="summary-row">
					<view class="summary-label">累计销售总额：</view>
					<view class="summary-value">￥536856</view>
					<view class="partner-badge"><image src="/static/partner-crown.png" class="crown"/>合伙人</view>
				</view>
				<view class="summary-split">
					<view class="summary-item">
						<view class="item-label">当月销售额（元）</view>
						<view class="item-value">15680</view>
					</view>
					<view class="summary-item">
						<view class="item-label">季度销售额（元）</view>
						<view class="item-value">68598</view>
					</view>
					<view class="summary-item">
						<view class="item-label">年度销售额（元）</view>
						<view class="item-value">168526</view>
					</view>
				</view>
			</view>
		</view>



		<!-- 商品销量列表 -->
		<view v-if="hasLogin">
			<scroll-view scroll-x class="h-list-history"  style="height:100vh">
		<view class="product-sales">
			<view class="section-title">
				<text class="iconfont icon-goods" style="margin-right:8px;">&#xe60a;</text>
				按商品显示销量
			</view>

			<!-- <rf-product-list :bottom="bottom" :list="productList"></rf-product-list> -->



			<view class="product-sale-item" v-for="item in productList" :key="item.id">
				<image :src="item.picture" class="product-img" />
				<view class="product-info">
					<view class="product-title">{{ item.name }}</view>
					<view class="product-desc">累计销量：{{ item.saleinfo.totalCount }} 件 累计销售额：{{ item.saleinfo.totalAmount }}元</view>
					<view class="product-desc">本月销售：{{ item.saleinfo.monthAmount }}元 季度销售：{{ item.saleinfo.quarterAmount }}元 年度销售：{{ item.yearAmount }}元</view>
				</view>
			</view>


			<rf-load-more
				:status="loadingType"
				v-if="productList.length > 0"
			></rf-load-more>
			<rf-empty
				:info="errorInfo || '该分类暂无商品'"
				v-if="productList.length === 0 && !loading"
			></rf-empty>


		</view>
		</scroll-view>
		</view>


	<tabBar active="wenchuang"></tabBar>
	</view>
</template>

<script>
	import {
		indexList,
		productList,
		productDetail
	} from '@/api/product';
import rfSwipeDot from '@/components/rf-swipe-dot';
import rfFloorIndex from '@/components/rf-floor-index';
import rfSearchBar from '@/components/rf-search-bar';
import rfSwiperSlide from '@/components/rf-swiper-slide';
import rfProductList from '@/components/rf-product-list';
import listCell from '@/components/rf-list-cell';
	import rfLoadMore from '@/components/rf-load-more/rf-load-more';

import { footPrintList, memberInfo, notifyUnRreadCount } from '@/api/userInfo';
import { mapMutations } from 'vuex';
import rfBadge from '@/components/rf-badge/rf-badge';
import $mAssetsPath from '@/config/assets.config';
let startY = 0, moveY = 0, pageAtTop = true;
export default {
	components: {
		listCell,
		rfBadge,

		rfFloorIndex,
		rfSwipeDot,
		rfProductList,
		rfSearchBar,
		listCell,
		rfSwiperSlide,
		rfLoadMore
	},
	data() {
		return {
			hasLogin: false,
			keyword: '',
			errorInfo: '',
			loadingType: 'more',
			page: 1,
			price: "",
			loading: true,
			productList: [
			],

			categoryProductList: [], // 分类列表
			orderSectionList: this.$mConstDataConfig.orderSectionList,
			amountList: this.$mConstDataConfig.amountList,
			isOpenLiveStreaming: this.$mSettingConfig.isOpenLiveStreaming,
			headImg: this.$mAssetsPath.headImg,
			vipCardBg: this.$mAssetsPath.vipCardBg,
			arc: this.$mAssetsPath.arc,
			userBg: this.$mAssetsPath.userBg,
			coverTransform: 'translateY(0px)',
			coverTransition: '0s',
			moving: false,
			userInfo: {
				// 用户信息
				promoter: null // 分销商信息
			},
			footPrintList: [], // 足迹列表
			loading: true,
			appName: this.$mSettingConfig.appName,
			hasLogin: false,
			currentLanguage: this._i18n.locale === 'zh' ? 'English' : '中文',
			sales: [
				]
		};
	},
	filters: {
		filterMemberLevel(val) {
      if (!val) return '普通用户';
			return val.name;
		},
		marketingTypeTag(marketingType) {
			let tag;
			switch (marketingType) {
				case 'discount':
					tag = $mAssetsPath.discountTag;
					break;
				case 'bargain':
					tag = $mAssetsPath.bargainTag;
					break;
				case 'group_buy':
					tag = $mAssetsPath.groupTag;
					break;
				case 'wholesale':
					tag = $mAssetsPath.wholesaleTag;
					break;
			}
			return tag;
		}
	},
  computed: {
		statusBar () {
			const e = uni.getSystemInfoSync();
			return e.statusBarHeight;
		},
		bottom () {
			let bottom = 0;
			/*  #ifdef H5  */
			bottom = 90;
			/*  #endif */
			return bottom;
		},
    // 判断推广中心是否显示 当有分销商信息的时候显示
    settingItemShowFilter() {
      return function (val) {
        let type = 'block';
        if (val === '推广中心' && this.userInfo.promoter) {
          type = 'none';
        } else if (val === '直播' && !this.isOpenLiveStreaming) {
          type = 'none';
        }
        return type;
      };
    },
		settingList() {
			return [
				{ icon: 'icongonggao', url: '/pages/index/notice/notice', title: this._i18n.t('profile.notice'), color: '#ff6b81' },
				{ icon: 'iconyouhuiquan-copy', url: '/pages/user/coupon/list', title: this._i18n.t('profile.couponCenter'), color: '#ff6b81' },
				{ icon: 'icondizhi1', url: '/pages/user/address/address', title: this._i18n.t('profile.addressManage'), color: '#ff6b81' },
				{ icon: 'iconshoucang3', url: '/pages/user/collection/collection', title: this._i18n.t('profile.myCollection'), color: '#ff6b81' },
				{ icon: 'iconfenxiang', url: '', title: this._i18n.t('profile.share'), color: '#ff6b81' },
				{ icon: 'iconzhibo', url: '/pages/marketing/live/list', title: this._i18n.t('profile.live'), color: '#ff6b81' },
				{ icon: 'iconshezhi3', url: '/pages/set/set', title: this._i18n.t('profile.setting'), color: '#ff6b81' }
			];
		}
  },
	// 小程序分享
	onShareAppMessage() {
		return {
			title: `欢迎来到${this.appName}`,
			path: '/pages/index/index'
		};
	},
	async onShow() {
		// 初始化数据
		await this.initData();
	},
	// #ifndef MP
	onNavigationBarButtonTap(e) {
		const index = e.index;
		// if (index === 0) {
			this.navTo('/pages/set/set');
		// } else if (index === 1) {
		// 	// #ifdef APP-PLUS
		// 	// eslint-disable-next-line
		// 	const pages = getCurrentPages();
		// 	const page = pages[pages.length - 1];
		// 	const currentWebview = page.$getAppWebview();
		// 	currentWebview.hideTitleNViewButtonRedDot({
		// 		index
		// 	});
		// 	// #endif
		// 	this.$mRouter.switchTab({ route: '/pages/notify/notify' });
		// }
	},
	onReachBottom(e) {

		this.page += 1
		this.getProductList()
	},

	// #endif
	methods: {
		// 获取产品列表
		async getProductList() {
			await this.$http
				.get(`${productList}`, {
					page: this.page
				})
				.then(async r => {
					this.loading = false;
					this.productLoading = false;
					this.loadingType = r.data.length < 10 ? 'nomore' : 'more';
					this.productList = [...this.productList, ...r.data];
				}).catch(() => {
					this.loading = false;
					this.productLoading = false;
				});
		},
		// 切换语言
		switchLanguage() {
			if (this._i18n.locale === 'zh') {
				this._i18n.locale = 'en';
				this.currentLanguage = '中文';
			} else if (this._i18n.locale === 'en') {
				this._i18n.locale = 'zh';
				this.currentLanguage = 'English';
			}
			this.initData();
			this.$mStore.commit('setLocale', this._i18n.locale);
			uni.setNavigationBarTitle({ title: this._i18n.t('menu.my') });
			uni.setTabBarItem({ index: 0, text: this._i18n.t('menu.index') });
			uni.setTabBarItem({ index: 1, text: this._i18n.t('menu.category') });
			uni.setTabBarItem({ index: 2, text: this._i18n.t('menu.notify') });
			uni.setTabBarItem({ index: 3, text: this._i18n.t('menu.cart') });
			uni.setTabBarItem({ index: 4, text: this._i18n.t('menu.my') });
		},
		...mapMutations(['setNotifyNum', 'setCartNum']),
		// 分享
    share() {
			const url = `${this.$mConfig.hostUrl}/pages/index/index`;
      // #ifdef H5
			this.$mHelper.h5Copy(url);
			// #endif
      // #ifdef APP-PLUS
			const shareImg = `${this.$mSettingConfig.appLogo}`;
			this.$mHelper.handleAppShare(url, this.appName, `欢迎来到${this.appName}`, shareImg);
			// #endif
		},
		...mapMutations(['login']),
		// 数据初始化
		async initData() {
			this.hasLogin = this.$mStore.getters.hasLogin;
			console.log(this.hasLogin)
			uni.setTabBarStyle({
				selectedColor: this.themeColor.color,
				borderStyle: 'white'
			});
			this.themeColor.tabList && this.themeColor.tabList.forEach((selectedIconPath, index) => {
				uni.setTabBarItem({
					index,
					selectedIconPath
				});
			});
			if (this.hasLogin) {
				await this.getMemberInfo();
			} else {
				this.loading = false;
				this.resetSectionData();
			}
		},
		// 获取用户信息
		async getMemberInfo() {
			await this.$http
				.get(memberInfo)
				.then(async r => {
					this.loading = false;
					this.userInfo = r.data;
					console.log(this.userInfo)
					await this.getProductList()
					// await this.setCartNum(r.data.cart_num);
					// await this.initNotifyNum();
					// 获取足迹列表
					// await this.getFootPrintList();
					// await this.setSectionData(r.data);
				})
				.catch((e) => {
					console.log("111",e)
					this.hasLogin = false;
					this.userInfo = {};
					this.resetSectionData();
					this.loading = false;
				});
		},
		// 设置未读消息个数
		async initNotifyNum () {
      await this.$http.get(notifyUnRreadCount).then(r => {
        this.setNotifyNum(r.data.count);
      });
    },
		// 清空个人中心的各模块状态
		resetSectionData() {
			this.userInfo = {};
			uni.removeTabBarBadge({ index: this.$mConstDataConfig.cartIndex });
			uni.removeTabBarBadge({ index: this.$mConstDataConfig.notifyIndex });
			this.amountList[0].value = 0;
			this.amountList[1].value = 0;
			this.amountList[2].value = 0;
			this.orderSectionList[0].num = 0;
			this.orderSectionList[1].num = 0;
			this.orderSectionList[2].num = 0;
			this.orderSectionList[3].num = 0;
			this.orderSectionList[4].num = 0;
		},
		// 给个人中心的各模块赋值
		setSectionData(data) {
			const orderSynthesizeNumArr = [];
			for (let item in data.order_synthesize_num) {
				orderSynthesizeNumArr.push(data.order_synthesize_num[item]);
			}
			for (let i = 0; i < this.orderSectionList.length; i++) {
				this.orderSectionList[i].num = orderSynthesizeNumArr[i].toString();
			}
			this.amountList[0].value = data.account.user_money || 0;
			this.amountList[1].value = data.coupon_num || 0;
			this.amountList[2].value = data.account.user_integral || 0;
			// 更新userInfo缓存
			uni.setStorageSync('userInfo', data);
		},
		// 获取足迹列表
		async getFootPrintList() {
			await this.$http.get(`${footPrintList}`).then(r => {
				this.footPrintList = r.data;
			});
		},
		// 统一跳转接口,拦截未登录路由
		navTo(route) {
			if (!route) return;
			if (route === '/pages/index/notice/notice') {
				this.$mRouter.push({ route });
			} else if (!this.hasLogin) {
				uni.removeStorageSync('backToPage');
				this.$mRouter.push({ route: '/pages/public/logintype' });
			} else {
				this.$mRouter.push({ route });
			}
		},
		/**
		 *  会员卡下拉和回弹
		 *  1.关闭bounce避免ios端下拉冲突
		 *  2.由于touchmove事件的缺陷（以前做小程序就遇到，比如20跳到40，h5反而好很多），下拉的时候会有掉帧的感觉
		 *    transition设置0.1秒延迟，让css来过渡这段空窗期
		 *  3.回弹效果可修改曲线值来调整效果，推荐一个好用的bezier生成工具 http://cubic-bezier.com/
		 */
		coverTouchstart(e) {
			if (pageAtTop === false) {
				return;
			}
			this.coverTransition = 'transform .1s linear';
			startY = e.touches[0].clientY;
		},
		coverTouchmove(e) {
			moveY = e.touches[0].clientY;
			let moveDistance = moveY - startY;
			if (moveDistance < 0) {
				this.moving = false;
				return;
			}
			this.moving = true;
			if (moveDistance >= 80 && moveDistance < 100) {
				moveDistance = 80;
			}
			if (moveDistance > 0 && moveDistance <= 80) {
				this.coverTransform = `translateY(${moveDistance}px)`;
			}
		},
		coverTouchend() {
			if (this.moving === false) {
				return;
			}
			this.moving = false;
			this.coverTransition = 'transform 0.3s cubic-bezier(.21,1.93,.53,.64)';
			this.coverTransform = 'translateY(0px)';
		},
		// 跳转至商品详情
		navToProduct(type, id) {
			let route = `/pages/product/product?id=${id}`;
			switch (type) {
				case 'discount':
					route = `/pages/marketing/discount/product?id=${id}`;
					break;
				case 'bargain':
					route = `/pages/marketing/bargain/product?id=${id}`;
					break;
				case 'group_buy':
					route = `/pages/marketing/group/product?id=${id}`;
					break;
				case 'wholesale':
					route = `/pages/marketing/wholesale/product?id=${id}`;
					break;
			}
			this.$mRouter.push({ route });
		}
	}
};
</script>
<style lang="scss" scoped>
page {
	background-color: $page-color-base;
}
.partner-profile {
	min-height: 100vh;
	background: #f8f8f8;
	padding-bottom: 80px;
	.profile-header {
		position: relative;
		width: 100%;
		height: 180px;
		.header-bg {
			background: #1ec6b6;
			width: 100%;
			height: 460rpx;
			position: absolute;
			left: 0; top: 0;
			z-index: 1;
			border-bottom-left-radius: 40px;
			border-bottom-right-radius: 40px;
		}
		.avatar-box {
			position: absolute;
			left: 50%;
			top: 38px;
			transform: translateX(-50%);
			z-index: 2;
			.avatar {
				width: 96px;
				height: 96px;
				border-radius: 50%;
				border: 6px solid #fff;
				background: #fff;
			}
		}
		.name {
			position: absolute;
			left: 0; right: 0;
			top: 140px;
			text-align: center;
			font-size: 22px;
			color: #fff;
			font-weight: bold;
			z-index: 2;
			letter-spacing: 2px;
		}
	}
	.sales-summary {
		margin: 40px 0 0 0;
		padding: 0 16px;
		.summary-main {
			z-index:999;
			background: #ff6c0e;
			border-radius: 28px;
			color: #fff;
			padding: 24px 18px 18px 18px;
			box-shadow: 0 2px 8px #f3e2d0;
			position: relative;
			.summary-row {
				display: flex;
				align-items: center;
				justify-content: flex-start;
				font-size: 18px;
				margin-bottom: 18px;
				.summary-label {
					font-size: 16px;
				}
				.summary-value {
					font-size: 22px;
					font-weight: bold;
					margin-left: 8px;
				}
				.partner-badge {
					margin-left: auto;
					background: #ffd465;
					color: #b06a00;
					border-radius: 16px;
					padding: 2px 12px 2px 8px;
					font-size: 15px;
					display: flex;
					align-items: center;
					.crown {
						width: 22px;
						height: 22px;
						margin-right: 4px;
					}
				}
			}
			.summary-split {
				display: flex;
				justify-content: space-between;
				.summary-item {
					flex: 1;
					text-align: center;
					.item-label {
						font-size: 14px;
						color: #ffe0c2;
						margin-bottom: 6px;
					}
					.item-value {
						font-size: 20px;
						font-weight: bold;
						color: #fff;
					}
				}
			}
		}
	}
	.product-sales {
		margin: 24px 0 0 0;
		padding: 0 12px;
		.section-title {
			background: linear-gradient(90deg, #1ec6b6 60%, #e6f6f3 100%);
			color: #fff;
			font-size: 18px;
			border-radius: 12px;
			padding: 8px 18px;
			margin-bottom: 12px;
			display: flex;
			align-items: center;
			.iconfont {
				font-size: 20px;
			}
		}
		.product-sale-item {
			display: flex;
			align-items: flex-start;
			background: #fff;
			border-radius: 12px;
			margin-bottom: 14px;
			padding: 12px 10px;
			.product-img {
				width: 72px;
				height: 72px;
				border-radius: 8px;
				margin-right: 12px;
				object-fit: cover;
				background: #f3f3f3;
			}
			.product-info {
				flex: 1;
				.product-title {
					font-size: 18px;
					color: #333;
					font-weight: bold;
					margin-bottom: 4px;
				}
				.product-desc {
					font-size: 14px;
					color: #888;
					margin-bottom: 2px;
				}
			}
		}
	}
	.tabbar {
		position: fixed;
		left: 0; right: 0; bottom: 0;
		height: 60px;
		background: #fff;
		border-top: 1px solid #eee;
		display: flex;
		justify-content: space-around;
		align-items: center;
		z-index: 10;
		.tab {
			flex: 1;
			text-align: center;
			color: #bfa16b;
			font-size: 16px;
			&.active {
				color: #1ec6b6;
				font-weight: bold;
			}
		}
	}
}
%flex-center {
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
}
%section {
	justify-content: space-around;
	display: flex;
	align-content: center;
	background: #fff;
	border-radius: 10upx;
}
</style>
